<script>
import { checkLogin } from './libs/login';
import { HTTP_REQUEST_URL } from './config/app';
import { LOGIN_STATUS } from "./config/cache.js"
import { getShopConfig, silenceAuth, getLogo } from '@/api/public';
import Auth from '@/libs/wechat.js';
import Routine from './libs/routine.js';
import { colorChange, copyRight } from '@/api/api.js';
import { getUserInfo } from "@/api/user.js"
import { mapGetters } from "vuex"
import { silenceBindingSpread } from "@/utils/index.js";
import {
    getPublicData,
    createQuickOrder,
    createPublicQuickOrder,
    getProductDetail,
    createSaleOrder, createzfbSaleOrder, getSfFee
} from "./api/leaseOrder";
import { bindingAlipayAuth, getUserOpenid, quickAlipayPhone } from "./api/public";
import { depositPay, orderPay, orderPublicPay } from "./api/order";
import { getZeroVipStatus } from "@/utils/order";
// #ifdef MP
// let livePlayer = requirePlugin('live-player-plugin')
// #endif
let green =
    '--view-theme: #42CA4D;--view-priceColor:#FF7600;--view-minorColor:rgba(108, 198, 94, 0.5);--view-minorColorT:rgba(66, 202, 77, 0.1);--view-bntColor:#FE960F;--view-gradient:#4DEA4D'
let red =
    '--view-theme: #e93323;--view-priceColor:#e93323;--view-minorColor:rgba(233, 51, 35, 0.5);--view-minorColorT:rgba(233, 51, 35, 0.1);--view-bntColor:#FE960F;--view-gradient:#FF7931'
let blue =
    '--view-theme: #1DB0FC;--view-priceColor:#FD502F;--view-minorColor:rgba(58, 139, 236, 0.5);--view-minorColorT:rgba(9, 139, 243, 0.1);--view-bntColor:#22CAFD;--view-gradient:#5ACBFF'
let pink =
    '--view-theme: #FF448F;--view-priceColor:#FF448F;--view-minorColor:rgba(255, 68, 143, 0.5);--view-minorColorT:rgba(255, 68, 143, 0.1);--view-bntColor:#282828;--view-gradient:#FF67AD'
let orange =
    '--view-theme: #FE5C2D;--view-priceColor:#FE5C2D;--view-minorColor:rgba(254, 92, 45, 0.5);--view-minorColorT:rgba(254, 92, 45, 0.1);--view-bntColor:#FDB000;--view-gradient:#FF9451'
let gold =
    '--view-theme: #E0A558;--view-priceColor:#DA8C18;--view-minorColor:rgba(224, 165, 88, 0.5);--view-minorColorT:rgba(224, 165, 88, 0.1);--view-bntColor:#1A1A1A;--view-gradient:#FFCD8C'
let black =
    '--view-theme: #1a1a1a;--view-priceColor:#1a1a1a;--view-minorColor:rgba(236, 212, 168,0.8);--view-minorColorT:rgba(236, 212, 168,0.5);--view-bntColor:#1a1a1a;--view-gradient:#1a1a1a'
export default {
    globalData: {
        spid: 0,
        code: 0,
        isLogin: false,
        userInfo: {},
        MyMenus: [],
        globalData: false,
        isIframe: false,
        tabbarShow: true,
        windowHeight: 0,
        goodsId: '',
        orderId: '',
        storeId: '',
        // 快捷下单
        quickFirstData: {}, // 快捷下单：第一次回调
        quickFirstExtra: {},
        quickFrom: '',
        //  快捷下单：购买
        quickSaleExtra: {},
        // 公域商品：活动类型
        tag: '',
        // 渠道推广：灯火biz_no
        biz_no: '',
        // 渠道推广：渠道编码cno
        cno: '',
        // 渠道推广：渠道落地页参数
        lightParams: '',
        // 是否是从代客下单页面进入
        isDaike: false,
        // 自定义tabbar
        publicFooter: false,
        // 0元租包：是否开启
        zeroVipStatus: false,

        qrCode: '', // 解析的支付宝二维码参数
    },
    computed: mapGetters(['isLogin', 'cartNum']),
    watch: {
        isLogin: {
            deep: true, //深度监听设置为 true
            handler: function (newV, oldV) {
                if (newV) {
                    // this.getCartNum()
                } else {
                    this.$store.commit('indexData/setCartNum', '')
                }
            }
        },
        cartNum(newCart, b) {
            this.$store.commit('indexData/setCartNum', newCart + '')
            if (newCart > 0) {
                uni.setTabBarBadge({
                    index: 3,
                    text: newCart > 99 ? '99+' : newCart + ''
                })
            } else {
                uni.hideTabBarRedDot({
                    index: 3
                })
            }
        }
    },
    onLaunch: function (option) {
        console.log('全局参数option', option)
        // todo 获取参数必须放在首位
        // 商品分享 
        if (option.query && option.query?.id) {
            if (option.path === 'pages/goods_details/index') {
                this.globalData.goodsId = option.query.id
            }
            if (option.path === 'pages/goods/lease_order_details/index') {
                this.globalData.orderId = option.query.order_id
            }
            if (option.path === 'pages/store/home/index') {
                this.globalData.storeId = option.query.id
            }
        }

        // 解析的支付宝二维码
        if (option.query && option.query.qrCode) {
            // 将二维码参数存入全局变量
            this.globalData.qrCode = option.query.qrCode;
        }
        uni.hideTabBar()
        //#ifdef APP
        plus.screen.lockOrientation("portrait-primary");
        //#endif
        let that = this;
        getLogo().then(res => {
            uni.setStorageSync('BASIC_CONFIG', res.data)
        });
        //获取配置
        copyRight().then(res => {
            let data = res.data;
            uni.setStorageSync('wechatStatus', data.wechat_status)
            // #ifndef APP-PLUS
            this.site_config = data.record_No;
            // #endif
            if (!data.copyrightContext && !data.copyrightImage) {
                data.copyrightImage = '/static/images/support.png'
            }
            uni.setStorageSync('copyNameInfo', data.copyrightContext);
            uni.setStorageSync('copyImageInfo', data.copyrightImage);
            // #ifdef MP
            uni.setStorageSync('MPSiteData', JSON.stringify({ site_logo: data.site_logo, site_name: data.site_name }));
            // #endif
        }).catch(err => {
            return this.$util.Tips({
                title: err.msg
            });
        });
        colorChange('color_change').then(res => {
            let navigation = res.data.navigation; //判断悬浮导航是否显示
            let statusColor = res.data.status; //判断显示啥颜色
            uni.setStorageSync('navigation', navigation);
            uni.$emit('navOk', navigation);
            uni.setStorageSync('statusColor', statusColor);
            uni.$emit('colorOk', statusColor);
            switch (res.data.status) {
                case 1:
                    uni.setStorageSync('viewColor', blue)
                    uni.$emit('ok', blue)
                    break;
                case 2:
                    uni.setStorageSync('viewColor', green)
                    uni.$emit('ok', green)
                    break;
                case 3:
                    uni.setStorageSync('viewColor', red)
                    uni.$emit('ok', red)
                    break;
                case 4:
                    uni.setStorageSync('viewColor', pink)
                    uni.$emit('ok', pink)
                    break;
                case 5:
                    uni.setStorageSync('viewColor', orange)
                    uni.$emit('ok', orange)
                    break;
                case 6:
                    uni.setStorageSync('viewColor', gold)
                    uni.$emit('ok', gold)
                    break;
                case 7:
                    uni.setStorageSync('viewColor', black)
                    uni.$emit('ok', black)
                    break;
                default:
                    uni.setStorageSync('viewColor', red)
                    uni.$emit('ok', red)
                    break
            }
        });
        // 通过vuex获取并储存商品详情,商品分类可视化的数据
        this.$store.dispatch("getDiyProduct");
        // 判断分销uid
        if (option.query?.spid) {
            that.$Cache.set('spid', option.query.spid);
            that.globalData.spid = option.query.spid;
            silenceBindingSpread();
        }
        // #ifdef APP-PLUS || H5
        uni.getSystemInfo({
            success: function (res) {
                // 首页没有title获取的整个页面的高度，里面的页面有原生标题要减掉就是视口的高度
                // 状态栏是动态的可以拿到 标题栏是固定写死的是44px
                let height = res.windowHeight - res.statusBarHeight - 44
                // #ifdef H5 || APP-PLUS
                that.globalData.windowHeight = res.windowHeight + 'px'
                // #endif
                // // #ifdef APP-PLUS
                // that.globalData.windowHeight = height + 'px'
                // // #endif

            }
        });
        // #endif
        // #ifdef MP
        if (HTTP_REQUEST_URL == '') {
            console.error(
                "请配置根目录下的config.js文件中的 'HTTP_REQUEST_URL'\n\n请修改开发者工具中【详情】->【AppID】改为自己的Appid\n\n请前往后台【小程序】->【小程序配置】填写自己的 appId and AppSecret"
            );
            return false;
        }
        if (option.query?.hasOwnProperty('scene')) {
            let val = that.$util.getUrlParams(decodeURIComponent(option.query.scene));
            switch (option.scene) {
                //扫描小程序码
                case 1047:
                    that.globalData.spid = val.spid === undefined ? val : val.spid;
                    break;
                //长按图片识别小程序码
                case 1048:
                    that.globalData.spid = val.spid === undefined ? val : val.spid;
                    that.globalData.code = option.query.scene;
                    break;
                //手机相册选取小程序码
                case 1049:
                    that.globalData.spid = val.spid === undefined ? val : val.spid;
                    that.globalData.code = option.query.scene;
                    break;
                //直接进入小程序
                case 1001:
                    that.globalData.spid = val.spid === undefined ? val : val.spid;
                    break;
            }
        }
        this.checkUpdateVersion();
        // #endif
        // getShopConfig().then(res => {
        // 	this.$store.commit('SETPHONESTATUS', res.data.status);
        // });
        // 获取导航高度；
        uni.getSystemInfo({
            success: function (res) {
                that.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 91;
            }
        });
        // #ifdef MP
        let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
        that.globalData.navH = menuButtonInfo.top * 2 + menuButtonInfo.height / 2;
        const version = uni.getSystemInfoSync().SDKVersion || ''
        if (Routine.compareVersion(version, '2.21.2') >= 0) {
            console.log(version)
            that.$Cache.set('MP_VERSION_ISNEW', true)
        } else {
            that.$Cache.set('MP_VERSION_ISNEW', false)
        }
        // #endif

        // #ifdef H5
        // 添加crmeb chat 统计
        var __s = document.createElement('script');
        __s.src = `${HTTP_REQUEST_URL}/api/get_script`;
        document.head.appendChild(__s);

        uni.getSystemInfo({
            success(e) {
                /* 窗口宽度大于420px且不在PC页面且不在移动设备时跳转至 PC.html 页面 */
                if (e.windowWidth > 420 && !window.top.isPC && !/iOS|Android/i.test(e.system)) {
                    window.location.pathname = '/static/html/pc.html';
                }
            }
        });
        if (option.query?.hasOwnProperty('type')) {
            this.globalData.isIframe = true;
        } else {
            this.globalData.isIframe = false;
        }
        // H5的微信网页授权
        // if (window.location.pathname !== '/' && !this.isWork()) {
        // 	let snsapiBase = 'snsapi_base';
        // 	let urlData = location.pathname + location.search;
        // 	if (!that.$store.getters.isLogin && uni.getStorageSync('authIng')) {
        // 		uni.setStorageSync('authIng', false)
        // 	}
        // 	if (!that.$store.getters.isLogin && Auth.isWeixin()) {
        // 		let code,
        // 			state,
        // 			scope = ''
        //
        // 		if (option.query.code instanceof Array) {
        // 			code = option.query.code[option.query.code.length - 1]
        // 		} else {
        // 			code = option.query.code
        // 		}
        //
        //
        // 		if (code && code != uni.getStorageSync('snsapiCode') && location.pathname.indexOf(
        // 				'/pages/users/wechat_login/index') === -1) {
        // 			// 存储静默授权code
        // 			uni.setStorageSync('snsapiCode', code);
        // 			try {
        // 				let res =  silenceAuth({
        // 					code: code,
        // 					snsapi: 'snsapi_base',
        // 					spread_spid: that.$Cache.get('spid')
        // 				}).catch(error => {
        // 					uni.hideLoading()
        // 					return this.$util.Tips({
        // 						title: error
        // 					})
        // 				});
        // 				uni.setStorageSync('snRouter', decodeURIComponent(decodeURIComponent(option.query
        // 					.back_url)));
        // 				if (res.data.key !== undefined && res.data.key) {
        // 					this.$Cache.set('snsapiKey', res.data.key);
        // 				} else {
        // 					let time = res.data.expires_time - this.$Cache.time();
        // 					this.$store.commit('LOGIN', {
        // 						token: res.data.token,
        // 						time: time
        // 					});
        //
        // 					this.$store.commit('SETUID', res.data.userInfo.uid);
        // 					this.$store.commit('UPDATE_USERINFO', res.data.userInfo);
        // 					if (option.query.back_url) {
        // 						location.replace(decodeURIComponent(decodeURIComponent(option.query
        // 							.back_url)));
        // 					}
        // 				}
        // 			} catch (e) {
        // 				let url = ''
        // 				if (option.query.back_url instanceof Array) {
        // 					url = option.query.back_url[option.query.back_url.length - 1]
        // 				} else {
        // 					url = option.query.back_url
        // 				}
        // 				if (!that.$Cache.has('snsapiKey')) {
        // 					if (location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
        // 						Auth.oAuth('snsapi_userinfo', url);
        // 					}
        // 				}
        // 			}
        // 		} else {
        // 			if (!this.$Cache.has('snsapiKey')) {
        // 				if (location.pathname.indexOf('/pages/users/wechat_login/index') === -1) {
        // 					Auth.oAuth(snsapiBase, urlData);
        // 				}
        // 			}
        // 		}
        // 	} else {
        // 		if (option.query.back_url) {
        // 			location.replace(uni.getStorageSync('snRouter'));
        // 		}
        // 	}
        // }
        // #endif
        // #ifdef MP-WEIXIN
        // 小程序静默授权
        if (!this.$store.getters.isLogin) {
            Routine.getCode().then(code => {
                this.silenceAuth(code);
            }).catch(res => {
                uni.hideLoading();
            });
        }
        // else if(this.$store.getters.isLogin && this.getExpired()){
        // 	//处理小程序有token情况下但是静默授权失败
        // 	this.$Cache.clear(LOGIN_STATUS);
        // 	Routine.getCode().then(code => {
        // 		this.silenceAuth(code);
        // 	})
        // }
        // #endif

        getZeroVipStatus()
    },
    onShow(options) {
        // #ifdef MP-ALIPAY
        // 快捷下单：三次回调
        this.quickFirst()
        this.quickSecond()
        this.quickCreatOrder()

        // 租售一体的售卖下单 + 详情下单一体页(售卖)
        this.quickSaleDetail()
        this.quickSaleCreate()
        this.$store.dispatch('getUserInfo')
        // #endif

        // 异步获取设备信息
        // uni.getSystemInfo({
        //   success: function (info) {
        //     console.log('设备信息：' + JSON.stringify(info))
        //     console.log('品牌：' + info.brand);
        //     console.log('型号：' + info.model);
        //     console.log('操作系统版本：' + info.system);
        //   }
        // });
        let that = this;
        //直播间分享
        // #ifdef MP
        // const sceneList = [1007, 1008, 1014, 1044, 1045, 1046, 1047, 1048, 1049, 1073, 1154, 1155];
        //  if (sceneList.includes(options.scene)) {
        // 	livePlayer.getShareParams()
        // 		.then(res => {
        // 			//记录推广人uid
        // 			if(res.custom_params.pid){
        // 				 that.$Cache.set('spid', res.custom_params.pid);
        // 				 that.globalData.spid = res.custom_params.pid;
        // 			}
        // 		}).catch(err => {
        // 		})
        // }
        // #endif

        // this.initFont()
    },
    methods: {
        // todo 快捷下单（购买商品） ：第一次回调（用户选择规格，地址）
        quickSaleDetail() {
            // uni.navigateBack({delta: 1})
            // my.navigateTo({
            //   url:`plugin://goodsDetailPlugin/rentGoodsDetail?outItemId=1`//outItemId：必填，商品编码
            // })
            // return
            let plugin = requirePlugin('goodsDetailPlugin');
            // 检查插件是否成功引入
            if (!plugin) {
                console.error('Plugin is not defined');
                return;
            }
            plugin.setDetailOrderInfoChangeCallback(async (params) => {
                // 商家需要在当前回调中完成以下内容：
                // 1.邮费的计算
                // 2.商家优惠计算
                // 3.当前商品sku是否限购、限购数量
                // 4.是否需要配置公告
                console.log('======>商品详情选择规格回调', params)
                console.log('==========>进入公域流程')
                const res = await new Promise((resolve, reject) => {
                    my.getAuthCode({
                        scopes: 'auth_base',
                        success: (res) => {
                            resolve(res);
                        },
                        fail: (err) => {
                            reject(err);
                        }
                    });
                })
                params.code = res.authCode
                let callbackData = await getProductDetail(params)
                this.globalData.quickSaleExtra = callbackData.data.extraParams
                console.log('==========>快捷下单购买，选择规格，回传参数', callbackData.data.params)
                return callbackData.data.params;
            });
        },
        quickSaleCreate() {
            let plugin = requirePlugin('goodsDetailPlugin');
            // 检查插件是否成功引入
            if (!plugin) {
                console.error('Plugin is not defined');
                return;
            }
            plugin.setDetailOrderSubmitOrderCallback(async (params) => {
                console.log('======>商品详情提交订单回调', params)
                my.showLoading();
                // my.confirm({
                //   content: JSON.stringify(params),
                // });
                //-------begin--------
                //TODO：此处需要开发者自行实现
                // 需要自己完成的步骤：
                // 1.调用前端接口来判断是否需要使用交易组件创建订单（参考https://opendocs.alipay.com/mini/084npr?pathHash=1a9f62f4）
                // 2.调用openapi创建业务单（参考https://opendocs.alipay.com/mini/54f80876_alipay.open.mini.order.create?pathHash=dffb8037）
                // 3.拉起收银台并支付（参考https://opendocs.alipay.com/mini/05xhsr?pathHash=d4709298）
                //-------end--------
                // 公域：用户登录
                let token = ''
                let expires_time = ''
                // 不判断是否登录，直接获取新的token
                // if(!this.$store.getters.isLogin){}
                const res = await new Promise((resolve, reject) => {
                    my.getAuthCode({
                        scopes: 'auth_base',
                        success: (res) => {
                            resolve(res);
                        },
                        fail: (err) => {
                            reject(err);
                        }
                    });
                });
                let loginForm = {
                    uuid: this.globalData.quickSaleExtra.uid,
                    code: res.authCode
                }
                console.log('======>0,快捷下单：登录参数', loginForm)
                // 快捷下单：登录接口
                const loginRes = await bindingAlipayAuth(loginForm)
                if (loginRes.status === 200) {
                    console.log('loginRes', loginRes)
                    let time = loginRes.data.expires_time - this.$Cache.time();
                    this.$store.commit('LOGIN', { token: loginRes.data.token, time: time });
                    this.$Cache.clear('snsapiKey');
                    console.log('======>0,快捷下单：登录成功')
                    token = loginRes.data.token
                    expires_time = loginRes.data.expires_time
                }


                // 1. 订单前置判断接口获取 sourceId
                const { requireOrder, sceneId, sourceId } = await new Promise((resolve, reject) => {
                    my.checkBeforeAddOrder({
                        success: resolve,
                        fail: reject
                    });
                });
                console.log('======>1,订单前置判断接口获取')

                params.extraParams = {
                    token: token,
                    expires_time: expires_time,
                    source_id: sourceId,
                    detail_path: '/pages/goods/order_details/index?',
                    ...this.globalData.quickSaleExtra
                }
                console.log('======>2,提交订单参数', params)

                let tradeNo = ''
                let callbackData = {}
                // 纯售卖
                if (this.globalData.quickSaleExtra.item_type === 'sale') {
                    // 创建订单
                    let resSale = await createzfbSaleOrder(params)
                    callbackData = resSale
                    // 创建支付单
                    let res = await orderPay({
                        uni: resSale.data.outOrderId,
                        from: "routine",
                        paytype: "alipay"
                    })
                    tradeNo = res.data.result.jsConfig.tradeNo
                } else {
                    // 租售一体的售卖
                    let res = await createSaleOrder(params)
                    tradeNo = res.data.tradeNo
                    callbackData = res
                }
                // 唤起支付 callbackData.data.tradeNo
                let that = this
                uni.requestPayment({
                    provider: 'alipay',
                    orderInfo: tradeNo,
                    success: (e) => {
                        console.log(e)
                        if (e.resultCode == "6001") {
                        } else {
                            that.$util.Tips({ title: '支付成功' })
                        }
                    },
                    fail: (e) => {
                        console.log('ALIPAY_PAY_fail', e);
                        that.$util.Tips({ title: '支付失败' })
                    },
                    complete: () => {
                        uni.navigateTo({
                            url: `/pages/goods/order_details/index?order_id=${callbackData.data.outOrderId}&token=${token}&expires_time=${expires_time}&from=sale`
                        })
                    },
                });
                // let that =this
                // orderPublicPay({
                //   uni: callbackData.data.outOrderId,
                //   paytype:'alipay',
                //   from:'ali_routine',
                //   quitUrl:'/pages/goods/order_details/index?order_id=' + callbackData.data.outOrderId
                // }).then(res=>{
                //   if(res.status===200){
                //     let status = res.data.status,
                //         orderId = res.data.result.order_id || '',
                //         jsConfig = res.data.result.jsConfig;
                //     switch (status) {
                //       case 'ALIPAY_PAY':
                //         console.log('ALIPAY_PAY_MP-ALIPAY');
                //         uni.requestPayment({
                //           provider: 'alipay',
                //           orderInfo: jsConfig.tradeNo,
                //           success: (e) => {
                //             console.log(e)
                //             if(e.resultCode=="6001"){
                //             }else{
                //               that.$util.Tips({ title: '支付成功' })
                //             }
                //           },
                //           fail: (e) => {
                //             console.log('ALIPAY_PAY_fail',e);
                //             that.$util.Tips({ title: '支付失败' })
                //           },
                //           complete: () => {
                //             uni.navigateTo({
                //               url: `/pages/goods/order_details/index?order_id=${callbackData.data.outOrderId}&token=${token}&expires_time=${expires_time}&from=qo`
                //             })
                //           },
                //         });
                //         break;
                //     }
                //   }
                // })
                my.hideLoading(); // 当回调逻辑结束时需要隐藏loading
            });
        },

        // todo 快捷下单：第一次回调  初始化订单
        async quickFirst() {
            let plugin = requirePlugin('goodsDetailPlugin');
            // 检查插件是否成功引入
            if (!plugin) {
                console.error('Plugin is not defined');
                return;
            }
            plugin.setRentOrderInitCallback(async (params) => {
                console.log('======>第一次回调', params)
                // 退出登录
                this.$store.commit('LOGOUT');
                console.log('公域：退出登录')

                // 公域：官方商品详情页进入下单页，静默登录
                if (this.globalData.quickFrom != 'myDetail') {
                    console.log('==========>进入公域流程')
                    const res = await new Promise((resolve, reject) => {
                        my.getAuthCode({
                            scopes: 'auth_base',
                            success: (res) => {
                                resolve(res);
                            },
                            fail: (err) => {
                                reject(err);
                            }
                        });
                    })
                    params.code = res.authCode
                    const createRes = await getPublicData(params)
                    console.log('===============>公域返回参数', createRes)
                    if (createRes.status === 200) {
                        this.globalData.quickFirstData = createRes.data.quickParams
                        this.globalData.quickFirstExtra = createRes.data.extraParams
                        return this.globalData.quickFirstData
                    }
                }
                return this.globalData.quickFirstData
            })
        },
        // todo 快捷下单：第二次回调  运费金额
        quickSecond() {
            let plugin = requirePlugin('goodsDetailPlugin');
            let that = this
            // 检查插件是否成功引入
            if (!plugin) {
                console.error('Plugin is not defined');
                return;
            }
            plugin.setRentOrderChangeCallback(async (params) => {
                console.log('地址回调参数', params)
                let freight = 0

                let sfParams = {
                    province: params.addressInfo.prov,
                    city: params.addressInfo.city,
                    area: params.addressInfo.area,
                    item_id: params.itemInfo.outItemId
                }
                const sfRes = await getSfFee(sfParams)

                if (sfRes.status === 200) {
                    freight = sfRes.data.freight
                }

                // 商家需要在当前回调中完成以下内容：
                // todo 计算邮费
                // 1.邮费的计算
                return {
                    // freight: this.globalData.quickFirstExtra.freight, // 商家实际计算出来的金额
                    freight: freight, // 商家实际计算出来的金额
                    success: true,
                };
            });
        },
        // todo 快捷下单：第三次回调  创建订单
        async quickCreatOrder() {
            let that = this
            let plugin = requirePlugin('goodsDetailPlugin');
            // 检查插件是否成功引入
            if (!plugin) {
                console.error('Plugin is not defined');
                return;
            }
            plugin.setRentOrderSubmitCallback(async (params) => {
                console.log('==========>确认下单参数', params)


                //-------begin--------
                //TODO：此处需要开发者自行实现
                // 需要自己完成的步骤：
                // 1.订单前置判断接口获取 sourceId
                // 2.调用openapi创建业务单（参考https://opendocs.alipay.com/mini/54f80876_alipay.open.mini.order.create?pathHash=dffb8037）
                // 3.返回交易组件订单号
                //-------end--------

                // 公域：用户登录
                let token = ''
                let expires_time = ''
                // 不判断是否登录，直接获取新的token
                // if(!this.$store.getters.isLogin){}
                const res = await new Promise((resolve, reject) => {
                    my.getAuthCode({
                        scopes: 'auth_base',
                        success: (res) => {
                            resolve(res);
                        },
                        fail: (err) => {
                            reject(err);
                        }
                    });
                });
                // 如果支付宝返回的用户信息为undefined：代表为申请实名信息权限（需要找小二）
                if (params.userInfo == undefined || !params.userInfo) {
                    params.userInfo = {
                        certNo: '',
                        mobileNum: '',
                        userName: '',
                    }
                }
                // 快捷下单：登录参数-内部接口
                let loginForm = {
                    uuid: this.globalData.quickFirstExtra.uid,
                    code: res.authCode,
                    cert_no: params.userInfo.certNo,
                    mobile: params.userInfo.mobileNum,
                    user_name: params.userInfo.userName
                }
                console.log('======>0,快捷下单：登录参数', loginForm)
                // 快捷下单：登录接口
                const loginRes = await bindingAlipayAuth(loginForm)
                if (loginRes.status === 200) {
                    console.log('loginRes', loginRes)
                    let time = loginRes.data.expires_time - this.$Cache.time();
                    this.$store.commit('LOGIN', { token: loginRes.data.token, time: time });
                    this.$Cache.clear('snsapiKey');
                    console.log('======>0,快捷下单：登录成功')
                    token = loginRes.data.token
                    expires_time = loginRes.data.expires_time
                }

                // 1. 订单前置判断接口获取 sourceId
                const { requireOrder, sceneId, sourceId } = await new Promise((resolve, reject) => {
                    my.checkBeforeAddOrder({
                        success: resolve,
                        fail: reject
                    });
                });
                console.log('======>1,订单前置判断接口获取')

                const { deviceModel, model } = await new Promise((resolve, reject) => {
                    uni.getSystemInfo({
                        success: resolve,
                        fail: reject
                    });
                });
                let dev = deviceModel || model

                // 2. 创建订单-获取交易组件订单
                params.extra = {
                    token: token,
                    expires_time: expires_time,
                    source_id: sourceId,
                    detail_path: '/pages/goods/lease_order_details/index?',
                    smid: this.globalData.quickFirstData.bizParamData.advanceRiskCtrlParam.subMerchantId,
                    current_phone_model: dev,
                    ...this.globalData.quickFirstExtra
                }
                console.log('======>2,快捷下单：创建参数', params)
                const createRes = await createPublicQuickOrder(params);
                return createRes.data
            });
        },
        // 小程序静默授权
        silenceAuth(code) {
            let that = this;
            let spid = that.globalData.spid ? that.globalData.spid : '';
            silenceAuth({
                code: code,
                spread_spid: spid,
                spread_code: that.globalData.code
            })
                .then(res => {
                    if (res.data.token !== undefined && res.data.token) {
                        uni.hideLoading();
                        let time = res.data.expires_time - this.$Cache.time();
                        that.$store.commit('LOGIN', {
                            token: res.data.token,
                            time: time
                        });
                        that.$store.commit('SETUID', res.data.userInfo.uid);
                        that.$store.commit('UPDATE_USERINFO', res.data.userInfo);
                    }
                }).catch(err => {
                    return that.$util.Tips({
                        title: err
                    })
                });
        },
        isWork() {
            return navigator.userAgent.toLowerCase().indexOf('wxwork') !== -1 && navigator.userAgent.toLowerCase()
                .indexOf("micromessenger") !== -1
        },
        /**
         * 检测当前的小程序
         * 是否是最新版本，是否需要下载、更新
         */
        checkUpdateVersion() {
            //判断微信版本是否 兼容小程序更新机制API的使用
            if (wx.canIUse('getUpdateManager')) {
                const updateManager = wx.getUpdateManager();
                //检测版本更新
                updateManager.onCheckForUpdate(function (res) {
                    if (res.hasUpdate) {
                        updateManager.onUpdateReady(function () {
                            wx.showModal({
                                title: '温馨提示',
                                content: '检测到新版本，是否重启小程序？',
                                showCancel: false,
                                success: function (res) {
                                    if (res.confirm) {
                                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                        updateManager.applyUpdate()
                                    }
                                }
                            })
                        })
                        updateManager.onUpdateFailed(function () {
                            // 新版本下载失败
                            wx.showModal({
                                title: '已有新版本',
                                content: '请您删除小程序，重新搜索进入',
                            })
                        })
                    }
                })
            } else {
                wx.showModal({
                    title: '溫馨提示',
                    content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
                })
            }
        },
        async getExpired() {
            // 通过一个个人中心的接口判断token是否生效，catch捕获到就证明token过期，返回true
            try {
                await getUserInfo();
                return false; // token有效
            } catch (err) {
                return true; // token过期
            }
        },

        // 字体设置
        async initFont() {
            // 1️⃣ 检查本地缓存
            let savedPath = uni.getStorageSync('cachedFont');
            if (typeof savedPath === 'object') savedPath = ''; // 过滤 { success: true }
            console.log('读取缓存字体：', savedPath)

            // 2 正确：启用缓存逻辑 + 添加异常处理
            if (savedPath) {
                console.log('使用缓存字体')
                this.loadFont(savedPath);
                return;
            }

            // 3️⃣ 无缓存时完整流程
            console.log('下载新字体')
            let tempPath = await this.downloadFont();
            savedPath = await this.saveFont(tempPath);
            this.loadFont(savedPath);
        },
        downloadFont() {
            return new Promise((resolve, reject) => { // 👈 修改为 reject 模式
                uni.downloadFile({
                    url: 'https://qn.ebaozu.cn/public/mini/font/PingFang-Regular.woff',
                    success: res => {
                        console.log('下载临时路径:', res.tempFilePath); // ✅ 检查路径格式
                        resolve(res.tempFilePath);
                    },
                    fail: reject // 👈 捕获下载错误
                });
            });
        },
        saveFont(tempPath) {
            return new Promise(resolve => {
                uni.saveFile({
                    tempFilePath: tempPath,
                    success: res => {
                        uni.setStorageSync('cachedFont', res.savedFilePath);
                        console.log('永久存储字体', res.savedFilePath)
                        resolve(res.savedFilePath);
                    },
                });
            });
        },
        loadFont(path) {
            // #ifdef MP-ALIPAY
            my.loadFontFace({
                family: 'MyFont',
                source: `url("${path}")`,
                global: true, // 必须添加此参数
                success() {
                    console.log('字体生效:', path);
                },
                fail(err) {
                    console.error('字体加载失败:', path, err);
                    uni.removeStorageSync('cachedFont');
                }
            });
            // #endif
        }
    },
};
</script>

<style lang="scss">
/* #ifndef APP-PLUS-NVUE || APP-NVUE */
@import url('@/plugin/emoji-awesome/css/tuoluojiang.css');
@import url('@/plugin/animate/animate.min.css');
@import 'static/css/base.css';
@import 'static/iconfont/iconfont.css';
@import 'static/iconfont/ebao-iconfont.css';
@import 'static/iconfont/ebao-iconfont-color.css';
@import 'static/css/unocss.css';
@import 'static/fonts/font.scss';
@import 'static/css/ohter.scss';

view {
    box-sizing: border-box;
}

page {
    font-family: PingFang SC;
}

.placeholder {
    color: #ccc;
}

.bg-color-red {
    background-color: var(--view-theme) !important;
}

.syspadding {
    padding-top: var(--status-bar-height);
}

.flex {
    display: flex;
}

.uni-scroll-view::-webkit-scrollbar {
    /* 隐藏滚动条，但依旧具备可以滚动的功能 */
    display: none;
}

::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
}

.uni-system-open-location .map-content.fix-position {
    height: 100vh;
    top: 0;
    bottom: 0;
}

/* #endif */
</style>
